/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package nhadat.dao;

import nhadat.entity.TblNguoiDung;
import nhadat.hibernate.HibernateUtil;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author Xe Bay
 */
public class NguoiDungDAO {

    private Session session;

    public NguoiDungDAO() {
        session = HibernateUtil.getSessionFactory().getCurrentSession();
    }

    public TblNguoiDung authenticate(String tendangnhap, String matkhau) {
        Transaction trans = null;
        try {
            trans = session.getTransaction();
            trans.begin();
            String sql = "From TblNguoiDung Where tendangnhap = ? and matkhau = ?";
            Query query = session.createQuery(sql);
            query.setString(0, tendangnhap);
            query.setString(1, matkhau);

            TblNguoiDung nguoiDung = (TblNguoiDung) query.uniqueResult();

            session.flush();
            trans.commit();
            return nguoiDung;
        } catch (Exception e) {
            if (trans.isActive()) {
                trans.rollback();
            }
            // e.printStackTrace();
            System.out.println(e.getMessage());
        }
        return null;
    }

    public boolean checkUserExit(String username) {
        Transaction trans = null;
        try {
            trans = session.getTransaction();
            trans.begin();
            String sql = "From TblNguoiDung Where tendangnhap = ?";
            Query query = session.createQuery(sql);
            query.setString(0, username);

            TblNguoiDung nguoiDung = (TblNguoiDung) query.uniqueResult();

            if (nguoiDung != null) {
                return true;
            }
            session.flush();
            trans.commit();

        } catch (Exception e) {
            if (trans.isActive()) {
                trans.rollback();
            }
            // e.printStackTrace();
            System.out.println(e.getMessage());
        }
        return false;
    }

    public void insertUser(TblNguoiDung nguoidung) {
        session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction trans = null;
        try {
            trans = session.getTransaction();
            trans.begin();
            NguoiDungDAO userDao = new NguoiDungDAO();

            session.save(nguoidung);

            session.flush();
            session.getTransaction();
            trans.commit();

        } catch (Exception e) {
            if (session.getTransaction().isActive()) {
                session.getTransaction().rollback();
            }
            e.printStackTrace();
        }
    }
}
